require('../common/utils.js')
const dotenv = require('dotenv')
const path = require('path');
const regex = /\${(\w+)}/g;
const useEnv = {}

let rawArgv = process.argv.slice(2)
let args = require('minimist')(rawArgv, {
  boolean: [
    'docker',
    // build
    // FIXME: --no-module, --no-unsafe-inline, no-clean, etc.
    'modern',
    'report',
    'report-json',
    'inline-vue',
    'watch',
    // serve
    'open',
    'copy',
    'https',
    // inspect
    'verbose'
  ]
})

let mode = args.mode
// rawArgv = rawArgv.slice(args._.length)
const index1 = rawArgv.indexOf("--mode=" + mode);
const index2 = rawArgv.indexOf("--mode");
if (index1 !== -1) {
  rawArgv.splice(index1, 1);
} else if (index2 !== -1) {
  rawArgv.splice(index2, 2);
}

const [command, arg] = args._;
// rawArgv.unshift(command);

if (command === 'serve') {
  mode = 'dev.' + (arg || 'server');
  useEnv.BABEL_ENV = useEnv.NODE_ENV = 'development';
} else if (command === 'prod') {
  mode = 'production';
  useEnv.BABEL_ENV = useEnv.NODE_ENV = 'production';
} else if (arg) {
  mode = 'prod.' + arg;
  useEnv.BABEL_ENV = useEnv.NODE_ENV = 'production';
} else {
  mode = 'development';
  useEnv.BABEL_ENV = useEnv.NODE_ENV = 'development';
}

if (!mode) {
  console.error('Invalid command line arguments');
  process.exit(1);
}
args.mode = mode



let contextPath = process.cwd()
// INIT_CWD = contextPath
let envPath = path.resolve(contextPath, `.env`)
let envPath1 = path.resolve(contextPath, `.env.${mode}`)
let envPath2 = path.resolve(contextPath, `.env.${mode}.local`)


function loadEnv(envPath) {
  let env = dotenv.config({ path: envPath, debug: process.env.DEBUG })
  parseEnv(env.parsed)
  Object.assign(useEnv, env.parsed)
  parseEnv(useEnv)
}

loadEnv(envPath)
loadEnv(envPath1)
loadEnv(envPath2)


parseEnv(useEnv)

function parseEnv(env){
  for (let k in env) {
    parseEnvItem(k, env)
  }
}
function parseEnvItem(k, env){
  let match;
  while ((match = regex.exec(env[k])) !== null) {
    const key = match[1];
    if (!env[key]){
      continue
    }
    let val = parseEnvItem(key, env)
    env[k] = env[k].replace(new RegExp('\\$\\{' + key + '\\}', 'gm'), val)
  }
  return env[k]
}

module.exports = {
  useEnv,
  args,
  rawArgv
}
